package com.kaili.common.tenant;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 动态数据源
 * @Copyright: Copyright (c) 2017
 * @Company: 杭州凯立通信有限公司
 * @author zhengs
 * @version 1.0.0 2018年4月10日 下午3:18:32
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
	@Autowired
	private MultiDataSourcePool multiDataSourcePool;
	
    /**
     * 获取当前数据源key
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return DbContextHolder.getDbType();
    }
    
    /**
     * 获取当前数据源
     */
    @Override
	protected DataSource determineTargetDataSource() {
		Object lookupKey = determineCurrentLookupKey();
		DataSource dataSource = null;
		try {
			dataSource = multiDataSourcePool.getDataSource(String.valueOf(lookupKey));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataSource;
	}
}